﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;

namespace TeBigScreenWpf
{
    using System.Timers;
    using Timer = System.Timers.Timer;

    /// <summary>
    /// Interaction logic for CrossWindow.xaml
    /// </summary>
    public partial class CrossWindow : Window
    {
        private class PageState
        {
            public Frame Frame;
            public PageItem Item;
            public bool Animate;
            public Page Current;

            public void Prev()
            {
                var idx = Item.Alternatives.IndexOf(Current);

                if (idx < 0)
                    ChangePage(Item.Alternatives[Item.Alternatives.Count - 1]);
                else if (idx == 0)
                    ChangePage(Item.Page);
                else
                    ChangePage(Item.Alternatives[idx - 1]);
            }

            public void Next()
            {
                var idx = Item.Alternatives.IndexOf(Current);

                if (idx < 0)
                    ChangePage(Item.Alternatives[0]);
                else if (idx == Item.Alternatives.Count - 1)
                    ChangePage(Item.Page);
                else
                    ChangePage(Item.Alternatives[idx + 1]);
            }

            private void ChangePage(Page p)
            {
                Current = p;
                Frame.Navigate(p);
            }
        }

        ContextMenu MyContextMenu => this.FindResource("cmWindow") as ContextMenu;

        private List<PageState> m_childs = new List<PageState>();

        private int VisualPageCount => ugrid_main.Children.Count;

        private Timer mTimer = new Timer();

        public CrossWindow(IList<PageItem> list, int row = 1, bool title = true)
        {
            InitializeComponent();

            this.PreviewMouseRightButtonUp += Window_PreviewMouseRightButtonUp;
            this.PreviewKeyUp += CrossWindow_PreviewKeyUp;

            ui_title.Visibility = title ? Visibility.Visible : Visibility.Collapsed;

            ugrid_main.Rows = row;

            foreach (var item in list)
            {
                var frame = new Frame { NavigationUIVisibility = NavigationUIVisibility.Hidden };
                frame.Navigate(item.Page);

                ugrid_main.Children.Add(frame);

                m_childs.Add(new PageState
                {
                    Frame = frame,
                    Item = item,
                    Animate = false,
                    Current = item.Page,
                });
            }

            CalcLayout();

            mTimer.Interval = 8000;
            mTimer.Elapsed += Timer_Elapsed;
            mTimer.Start();
        }

        private void CrossWindow_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            void ChangePage(int idx, bool next)
            {
                if (idx < m_childs.Count)
                {
                    var item = m_childs[idx];

                    if (next)
                        item.Next();
                    else
                        item.Prev();
                }
            }

            void AnimePage(int idx)
            {
                if (idx < m_childs.Count)
                {
                    var item = m_childs[idx];

                    item.Animate = !item.Animate;
                }
            }

            if (e.Key == Key.Up && Keyboard.Modifiers == ModifierKeys.Control)
                AnimePage(1);

            else if (e.Key == Key.Down && Keyboard.Modifiers == ModifierKeys.Control)
                AnimePage(1);

            else if (e.Key == Key.Left && Keyboard.Modifiers == ModifierKeys.Control)
                AnimePage(0);

            else if (e.Key == Key.Right && Keyboard.Modifiers == ModifierKeys.Control)
                AnimePage(2);


            else if (e.Key == Key.Up)
                ChangePage(1, false);

            else if (e.Key == Key.Down)
                ChangePage(1, true);


            else if (e.Key == Key.Left)
                ChangePage(0, true);

            else if (e.Key == Key.Right)
                ChangePage(2, true);
            
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            foreach (var item in m_childs)
            {
                if (item.Animate)
                    this.Dispatcher.InvokeAsync(() => item.Next());
            }
        }

        public void ShowFullScreen()
        {
            this.Show();
            this.SetFullScreen(VisualPageCount);
        }

        private void CalcLayout()
        {
            grid_main.Width = 2048 * VisualPageCount;
        }

        private void Window_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            void PrepareMenuItem()
            {
                if (LogicalTreeHelper.FindLogicalNode(MyContextMenu, "miPages") is MenuItem menu)
                {
                    menu.Items.Clear();

                    for (int i = 0; i < this.m_childs.Count; i++)
                    {
                        var pageitem = this.m_childs[i];

                        var menuitem = new MenuItem()
                        {
                            Name = $"miPages{i}",
                            Header = $"第{i + 1}页",
                        };

                        if (pageitem.Item.Alternatives.Count > 0)
                        {
                            var subitem = new MenuItem()
                            {
                                Header = "讲解",
                                IsCheckable = true,
                                IsChecked = pageitem.Animate,
                            };

                            subitem.Click += (o, ea) => pageitem.Animate = !pageitem.Animate;

                            menuitem.Items.Add(subitem);
                        }

                        menu.Items.Add(menuitem);
                    }
                }
            }

            PrepareMenuItem();
            ContextMenu cm = MyContextMenu;
            cm.PlacementTarget = sender as UIElement;
            cm.Tag = Mouse.GetPosition(this);
            cm.IsOpen = true;
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.InvokeAsync(() =>
            {
                if (e.Source is MenuItem mi)
                {
                    switch (mi.Name)
                    {
                        case "miFullscreen":
                            this.SetFullScreen(VisualPageCount);
                            break;

                        case "miFullscreenEx":
                            this.SetFullScreen(100);
                            break;

                        case "miRestore":
                            this.ResetFullScreen(VisualPageCount);
                            break;

                        case "miClose":
                            this.Close();
                            break;

                        default:
                            break;
                    }
                }
            });
        }
    }

    public class PageItem
    {
        public Page Page { get; set; }

        public List<Page> Alternatives { get; set; } = new List<Page>();
    }
}